/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Util/Error.h"

#include <WinSock2.h>

#ifndef __ERROR_MSG_SIZE__
#define __ERROR_MSG_SIZE__  0x200
#endif


static const char *getErrorMessage(int code, char* dest, std::size_t size)
{
	char *s = NULL;
	FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER 
		| FORMAT_MESSAGE_FROM_SYSTEM 
		| FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL, code,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPSTR)&s, 0, NULL);
	_snprintf_s(dest, size, _TRUNCATE, "%s", s);
	LocalFree(s);
	return dest;
}


int lastError(void)
{
	return GetLastError();
}

int lastNetError(void)
{
	return WSAGetLastError();
}

const char *getErrorString(char *dest, std::size_t size, int ec /* = lastError */)
{
	return getErrorMessage(ec, dest, size);
}

const char *getErrorString(::std::string &dest, int ec /* = lastError */)
{
	char errmsg[__ERROR_MSG_SIZE__];
	dest = getErrorMessage(ec, errmsg, sizeof(errmsg));
	return dest.c_str();
}

const ::std::string getErrorString(int ec /* = lastError */)
{
	char errmsg[__ERROR_MSG_SIZE__];
	getErrorMessage(ec, errmsg, sizeof(errmsg));
	return std::string(errmsg);
}